package cn.ffcs.contract.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.echoice.paper.PageBean;
import org.echoice.paper.PageNavi;
import org.echoice.util.DateUtil;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.TransactProcessStatus;
import cn.ffcs.bpmpvc.model.BpmAppInfo;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.svc.ProcessPvcService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.svc.TaskService;
import cn.ffcs.bpmpvc.web.FlowAppBaseAction;
import cn.ffcs.bpmpvc.web.PageNavUtil;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.contract.model.ActContract;
import cn.ffcs.contract.model.ContractBussout;
import cn.ffcs.contract.model.ContractInfo;
import cn.ffcs.contract.model.ContractRemind;
import cn.ffcs.contract.service.ContractRemindService;
import cn.ffcs.contract.service.ProjectService;
import cn.ffcs.contract.web.view.ContractBussoutView;
import cn.ffcs.organ.model.Organization;
import cn.ffcs.security.model.User;
import cn.ffcs.util.context.ApplicationContextUtil;

public class FlowContractInfoAction extends FlowAppBaseAction<TransactProcessStatus> {
	private final String JUMP_MSG = "jumpMsg";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private TaskService taskService;
	private ContractRemindService contractRemindService;
	private ProjectService projectService;
	private String flowTaskId;
	private String procinstId;
	private ProcessPvcService processPvcService;
	private ContractInfo contractInfoForm;
	private ContractBussoutView contractBussoutView;
	private AppBusinessReqService appBusinessReqService;
	
	public String showDetailBak() {
		String toPage = ApplicationContextUtil.getContextObject("toPage");
		TaskView taskView = getTaskService().getTaskView(flowTaskId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", taskView);
		ContractRemind contractRemind = getContractRemindService().getContractRemindDao().getByProcinstId(procinstId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("contractRemind", contractRemind);
		if (contractRemind != null) {
			Integer contractId = Integer.valueOf(contractRemind.getContractId());
			ContractInfo contractInfo = getContractRemindService().getContractRemindDao().getById(contractId);
			ApplicationContextUtil.getHttpServletRequest().setAttribute("contractInfo", contractInfo);
			String contractUrl = getContractUrl(contractInfo.getSignCode());
			ApplicationContextUtil.getHttpServletRequest().setAttribute("contractUrl", contractUrl);
			ContractRemind nextContractRemind = getContractRemindService().getContractRemindDao().getNextRemind(contractRemind);
			ApplicationContextUtil.getHttpServletRequest().setAttribute("nextContractRemind", nextContractRemind);
		}
		String taskType = taskView.getProcTranRecord().getTaskType();
		if ("03".equalsIgnoreCase(taskType)) {
			return "detailForRedo";
		}
		if (StringUtils.isNotBlank(toPage)) {
			return toPage;
		}

		return "detail";
	}

	public String showDetail() {
		String toPage = ApplicationContextUtil.getContextObject("toPage");
		TaskView taskView = getTaskService().getTaskView(flowTaskId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", taskView);
		// 取得业务数据
		getAppInfo();
		//
		String taskType = taskView.getProcTranRecord().getTaskType();
		if ("03".equalsIgnoreCase(taskType)) {
			return "detailForRedo";
		}
		if (StringUtils.isNotBlank(toPage)) {
			return toPage;
		}
		return "detail";
	}

	public String showInfo() {
		
		getAppInfo();
		// 取得流程实例及任务信息
		ProcessInstView processInstView = getProcessPvcService().getProcessInstView(Integer.valueOf(procinstId));
		ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", processInstView);
		// 取得当前流程运行节点信息
		setProcessInstTaskInfo(getTaskService(), processInstView, procinstId);
		return "contractInfo";
	}

	public String endProcessInst() throws Exception{
		String msg="";
		try{
			getTaskService().getFlowPvcDao().endProcessInst(String.valueOf(procinstId));
			msg="流程实例ID:"+procinstId+" 强制结束操作成功！";
		}catch (Exception e) {
			// TODO: handle exception
			msg=e.getMessage();
			e.printStackTrace();
		}
		rendTextExtjs(ApplicationContextUtil.getHttpServletResponse(),"{msg:'"+msg+"'}");
		return null;
	}
	
	private void getAppInfo() {
		BpmAppInfo bpmAppInfo = getContractRemindService().getAppBusinessReqService().getAppBusinessReqDao().getBpmAppInfo(procinstId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("bpmAppInfo", bpmAppInfo);
		if (bpmAppInfo != null) {
			Integer contractId = Integer.valueOf(bpmAppInfo.getAppId());
			getContractInfo(contractId);
			if ("01".equals(bpmAppInfo.getAppType())) {
				ContractRemind contractRemind = getContractRemindService().getContractRemindDao().getByProcinstId(procinstId);
				ApplicationContextUtil.getHttpServletRequest().setAttribute("contractRemind", contractRemind);
				if (contractRemind != null) {
					ContractRemind nextContractRemind = getContractRemindService().getContractRemindDao().getNextRemind(contractRemind);
					ApplicationContextUtil.getHttpServletRequest().setAttribute("nextContractRemind", nextContractRemind);
				}
			}
			String userId=ApplicationContextUtil.getUserContextObject().getCurrUser().getPersonID();
			if(userId.equalsIgnoreCase(bpmAppInfo.getStartUser())){
				ApplicationContextUtil.getHttpServletRequest().setAttribute("showEndBtn", "true");
			}
		}
		
	}
	
	private void getAppInfoBussOut() {
		ContractBussout contractBussout = getContractRemindService().getContractRemindDao().getContractBussout(procinstId);
		ContractBussoutView contractBussoutView=new ContractBussoutView();
		try {
			BeanUtils.copyProperties(contractBussoutView, contractBussout);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ApplicationContextUtil.getHttpServletRequest().setAttribute("contractBussoutView", contractBussoutView);
		if (contractBussout != null) {
			Integer contractId = Integer.valueOf(contractBussout.getContractId());
			getContractInfo(contractId);
			String userId=ApplicationContextUtil.getUserContextObject().getCurrUser().getPersonID();
			if(userId.equalsIgnoreCase(contractBussout.getUserId())){
				ApplicationContextUtil.getHttpServletRequest().setAttribute("showEndBtn", "true");
			}
		}
		
	}
	
	private void getContractInfo(Integer contractId){
		ContractInfo contractInfo = getContractRemindService().getContractRemindDao().getById(contractId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("contractInfo", contractInfo);
		String contractUrl = getContractUrl(contractInfo.getSignCode());
		ApplicationContextUtil.getHttpServletRequest().setAttribute("contractUrl", contractUrl);
	}
	
	private String getContractUrl(String signCode) {
		StringBuilder sbd = new StringBuilder();
		// 取得当前用户数据
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		ActContract actContract = projectService.findCUserInfoById(user.getUserID());
		if (actContract != null) {
			actContract.setContractID(projectService.findIdBySigncode(signCode));
			// 查找所在部门
			Organization organization = getContractRemindService().getAppBusinessReqService().getOrgByPerson(user.getPerson());
			if (organization != null) {
				actContract.setCurrDept(organization.getName());
			}
			actContract.setUserId(user.getUserID());
			actContract.setAct("modify");
			actContract.setFrameFlag("");
			actContract.setCompanyFlag("");
			String url = getContractRemindService().getConfigBean().getContractServiceUrl();
			sbd.append(url);
			sbd.append("?userID=" + actContract.getUserId());
			sbd.append("&userID_s=" + actContract.getUserMk());
			sbd.append("&redirectUrl=contract/contractLoadAction.do?act=" + actContract.getAct());
			sbd.append("&frameFlag=" + actContract.getFrameFlag());
			sbd.append("&companyFlag=" + actContract.getCompanyFlag());
			sbd.append("&currDept=" + actContract.getCurrDept());
			sbd.append("&ID=" + actContract.getContractID());
		}

		return sbd.toString();
	}

	public String commitTaskRemind() {
		String isCommitS = ApplicationContextUtil.getContextObject("isCommit");
		boolean isCommit = Boolean.valueOf(isCommitS);// 保存
		HttpServletRequest req = ApplicationContextUtil.getHttpServletRequest();
		// 下一步办理人
		List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
		// 抄送人员
		String content = req.getParameter("commentComtent");
		setCommitTaskMsg(isCommit);
		try {
			if (isCommit) {
				getTaskService().completeTask(flowTaskId, content, nextTasksList);
			} else {
				getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg = e.getMessage();
		}
		return "jumpMsg";
	}

	/**
	 * 合同约束提醒办理
	 * 
	 * @return
	 */
	public String commitDealTaskRemind() {
		String isCommitS = ApplicationContextUtil.getContextObject("isCommit");
		boolean isCommit = Boolean.valueOf(isCommitS);// 保存
		HttpServletRequest req = ApplicationContextUtil.getHttpServletRequest();
		// 下一步办理人
		List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
		String content = req.getParameter("commentComtent");
		setCommitTaskMsg(isCommit);
		try {
			String nextRemindId = ApplicationContextUtil.getContextObject("nextRemindId");
			ContractRemind contractRemind = null;
			if (StringUtils.isNotBlank(nextRemindId)) {
				contractRemind = new ContractRemind();
				contractRemind.setId(Integer.valueOf(ApplicationContextUtil.getContextObject("nextRemindId")));
				contractRemind.setCondNote(ApplicationContextUtil.getContextObject("nextRemindContent"));
				String dateStr = ApplicationContextUtil.getContextObject("nextCondTime");
				if (StringUtils.isNotBlank(dateStr)) {
					contractRemind.setCondTime(DateUtil.parse(dateStr, "yyyy-MM-dd"));
				}
			}
			getContractRemindService().saveDataAndCommitTaskOfDeal(flowTaskId, content, nextTasksList, isCommit, contractRemind);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg = e.getMessage();
		}
		return "jumpMsg";
	}

	protected void rendTextExtjs(HttpServletResponse response, String content) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/javascript;charset=UTF-8");
        response.getWriter().write(content);
    }
	
	public String saveRemind() {
		List<ContractRemind> list = new ArrayList<ContractRemind>();
		ContractRemind contractRemind = new ContractRemind();
		contractRemind.setCondTag("cond_tag_2");
		contractRemind.setCondNote("2222222");
		contractRemind.setCondTime(new Date());
		contractRemind.setContractId("9");
		contractRemind.setCondDo("1");
		list.add(contractRemind);
		getContractRemindService().getContractRemindDao().saveRemind(list, "9");
		return null;
	}

	
	public String findContractBussOutList(){
		HttpServletRequest request = ApplicationContextUtil.getHttpServletRequest();
		if(contractBussoutView==null){
			contractBussoutView=new ContractBussoutView();
		}
		PageBean pageBean=getContractRemindService().getContractRemindDao().findContractBussOutPage(contractBussoutView, PageNavUtil.getPageNo(request), PageNavUtil.getPageSize(request));
		request.setAttribute("datalist", pageBean.getDataList());
		String pageNaviStr = PageNavi.getPageNaviText(request, pageBean);
		request.setAttribute("pageNaviStr", pageNaviStr);
		return "validContractInfoBussOutList";
	}
	
	
	//查询可以进行业务退出的合同
	public String findValidContractList(){
		HttpServletRequest request = ApplicationContextUtil.getHttpServletRequest();
		if(contractInfoForm==null){
			contractInfoForm=new ContractInfo();
		}
		PageBean pageBean=getContractRemindService().getContractRemindDao().findValidContractPage(contractInfoForm, PageNavUtil.getPageNo(request), PageNavUtil.getPageSize(request));
		request.setAttribute("datalist", pageBean.getDataList());
		String pageNaviStr = PageNavi.getPageNaviText(request, pageBean);
		request.setAttribute("pageNaviStr", pageNaviStr);
		return "validContractInfoList";
	}
	
	
	//转向合同业务退出流程申请启动界面
	public String applyInit(){
		String processId=getAppBusinessReqService().getFlowContractBussOutProcessId();
		HttpServletRequest request = ApplicationContextUtil.getHttpServletRequest();
		String contractId=request.getParameter("contractId");
		getContractInfo(Integer.valueOf(contractId));
		ProcessView processView=getProcessPvcService().getInitProcessInfo(processId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("processView", processView);
		return "validContractInfoApplyInit";
	}
	//启动合同业务退出流程
	public String saveStartFlow() {
		String isCommitS = ApplicationContextUtil.getContextObject("isCommit");
		boolean isCommit = Boolean.valueOf(isCommitS);
		User user = ApplicationContextUtil.getUserContextObject().getCurrUser();
		HttpServletRequest req = ApplicationContextUtil.getHttpServletRequest();
		List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
		ContractBussout contractBussout=new ContractBussout();
		String outType=req.getParameter("outType");
		contractBussout.setOutType(Long.valueOf(outType));
		contractBussout.setOutContent(req.getParameter("outContent"));
		contractBussout.setContractId(req.getParameter("contractId"));
		setStartFlowMsg(isCommit);
		try {
			String processId =req.getParameter("processId");
			@SuppressWarnings("unused")
			ProcTranRecord procTranRecord = getContractRemindService().saveBussOutAndStartFlow(processId, user.getPerson(), nextTasksList, isCommit, contractBussout);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg = e.getMessage();
		}
		return JUMP_MSG;
	}
	
	public String commitAppylTask() {
		String procinstId=ApplicationContextUtil.getContextObject("procinstId");
		String flowTaskId=ApplicationContextUtil.getContextObject("flowTaskId");
        String isCommitS=ApplicationContextUtil.getContextObject("isCommit");
        boolean isCommit=Boolean.valueOf(isCommitS);//保存
        HttpServletRequest req=ApplicationContextUtil.getHttpServletRequest();
        List<TaskAssignBean> nextTasksList = getNextTaskUserList(req);
        String content=req.getParameter("commentComtent");
        ContractBussout contractBussout=getContractRemindService().getContractRemindDao().getContractBussout(procinstId);
		String outType=req.getParameter("outType");
		contractBussout.setOutType(Long.valueOf(outType));
		contractBussout.setOutContent(req.getParameter("outContent"));
		try {
			getContractRemindService().commitApplyTask(flowTaskId, content, nextTasksList, isCommit, contractBussout);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
            returnMsg=e.getMessage();
		}
        setCommitTaskMsg(isCommit);
		return JUMP_MSG;
	}
	
	public String showBussOut() {
		String toPage = ApplicationContextUtil.getContextObject("toPage");
		TaskView taskView = getTaskService().getTaskView(flowTaskId);
		ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", taskView);
		// 取得业务数据
		getAppInfoBussOut();
		//
		String taskType = taskView.getProcTranRecord().getTaskType();
		if ("03".equalsIgnoreCase(taskType)) {
			return "detailForRedoBussOut";
		}
		if (StringUtils.isNotBlank(toPage)) {
			return toPage;
		}
		return "detailBussOut";
	}
	
	public String showBussOutInfo() {
		getAppInfoBussOut();
		// 取得流程实例及任务信息
		ProcessInstView processInstView = getProcessPvcService().getProcessInstView(Integer.valueOf(procinstId));
		ApplicationContextUtil.getHttpServletRequest().setAttribute("taskView", processInstView);
		// 取得当前流程运行节点信息
		setProcessInstTaskInfo(getTaskService(), processInstView, procinstId);
		return "validContractInfo";
	}
	
	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public String getFlowTaskId() {
		return flowTaskId;
	}

	public void setFlowTaskId(String flowTaskId) {
		this.flowTaskId = flowTaskId;
	}

	public String getProcinstId() {
		return procinstId;
	}

	public void setProcinstId(String procinstId) {
		this.procinstId = procinstId;
	}

	public ContractRemindService getContractRemindService() {
		return contractRemindService;
	}

	public void setContractRemindService(ContractRemindService contractRemindService) {
		this.contractRemindService = contractRemindService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public ProcessPvcService getProcessPvcService() {
		return processPvcService;
	}

	public void setProcessPvcService(ProcessPvcService processPvcService) {
		this.processPvcService = processPvcService;
	}

	public ContractInfo getContractInfoForm() {
		return contractInfoForm;
	}

	public void setContractInfoForm(ContractInfo contractInfoForm) {
		this.contractInfoForm = contractInfoForm;
	}

	public AppBusinessReqService getAppBusinessReqService() {
		return appBusinessReqService;
	}

	public void setAppBusinessReqService(AppBusinessReqService appBusinessReqService) {
		this.appBusinessReqService = appBusinessReqService;
	}

	public ContractBussoutView getContractBussoutView() {
		return contractBussoutView;
	}

	public void setContractBussoutView(ContractBussoutView contractBussoutView) {
		this.contractBussoutView = contractBussoutView;
	}

}
